package com.gobygang.client;

/*
 * TODO
 *
 *
 */

import com.gobygang.client.Authenication.Provider;
import com.gobygang.client.Authenication.Status;
import com.gobygang.client.Session.UserAgent;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.TabPanel;


public class GobygangProcessor {

	private static final String ADMIN = "admin";
	private boolean adminMode;

	public GobygangProcessor(){
	}



	private final GobygangImageBundle tgib = (GobygangImageBundle)GWT.create(GobygangImageBundle.class);
	public static Anchor signOutLink = new Anchor("Sign Out");


	private boolean logedInFacebook;
	private long startTimeMillis;


	/**
	 * Fired when connect state is ready
	 */

	/**
	 * 
	 * browser:mozilla/5.0 (windows; u; cpu iphone;...
	 * browser:mozilla/5.0 (iphone; u; windows nt 6.0; de; rv:1.9.2) gecko/20100115 firefox/3.6 (.net clr 3.5.30729)
	 * browser:mozilla/5.0 (android; u; windows nt 6.0; de; rv:1.9.2) gecko/20100115 firefox/3.6 (.net clr 3.5.30729)
	 */

	public static native String getUserAgent() /*-{
	return navigator.userAgent.toLowerCase();
	}-*/;


	/**
	 * Note, we defer all application initialization code to
	 * {@link #onModuleLoad2()} so that the UncaughtExceptionHandler
	 * can catch any unexpected exceptions.
	 */
	TabPanel tabPanel;

	public void onModuleLoad(String locale,String country, String agent, String cron) {

		Session.getInstance().setTestAgent(agent);
		Session.getInstance().setCron(cron);

		/* Install an UncaughtExceptionHandler which will
		 * produce <code>FATAL</code> log messages
		 */
		//Log.setUncaughtExceptionHandler();

		//Log.info("onModuleLoad:"+locale+":"+country);

		/* Use a deferred command so that the UncaughtExceptionHandler
		 * catches any exceptions in onModuleLoad2()
		 */
		DeferredCommand.addCommand(new Command() {
			public void execute() {
				onModuleLoad2();
			}
		});
		GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
			public void onUncaughtException(Throwable e) {

				//Log.fatal("Uncaught exception: " + e);
				e.printStackTrace();
			}
		});

	}

	private void onModuleLoad2() {
		try {
			onModuleLoad3();
		} catch (Exception ex){
			Window.alert("onModuleLoad exception:"+ex);
			ex.printStackTrace();
		}
	}

	private void onModuleLoad3() {

		setStartCity();

		Session.getInstance().setIsLocalhost(GWT.getHostPageBaseURL().contains("http://127.0.0.1:8888/"));

		String modeParameter = Window.Location.getParameter("mode");
		String href = Window.Location.getHref();
		//Window.alert("mode="+href);
		Session.getInstance().setAdminMode(modeParameter != null && modeParameter.equals(ADMIN));
		Session.getInstance().setIsIncubator(href.contains("incubator2010"));

		Session.getInstance().setMapIsShown(false);
		String browser = getUserAgent();
		String userAgentRequestParameter = Window.Location.getParameter("userAgent");
		//Log.info("browser:"+browser);

		//assume PC
		Session.getInstance().setUserAgent(UserAgent.PC);			
		//Log.info("debug: userAgent:"+userAgentRequestParameter);

		if (userAgentRequestParameter!=null && userAgentRequestParameter.equals("FB_PAGE")){
			Session.getInstance().setUserAgent(UserAgent.FB_PAGE);

		} else {

			if (userAgentRequestParameter!=null && userAgentRequestParameter.equals("FB")){
				if (browser.contains("webkit")){
					Session.getInstance().setUserAgent(UserAgent.FB_WEBKIT);
				} else {
					Session.getInstance().setUserAgent(UserAgent.FB);	
				}
			} else{
				if (browser.contains("windows")){
					if (browser.contains("webkit")){
						Session.getInstance().setUserAgent(UserAgent.PC_WEBKIT);
					} else {
						Session.getInstance().setUserAgent(UserAgent.PC);					
					}
				} else 
					if (browser.contains("iphone")){
						Session.getInstance().setUserAgent(UserAgent.IPHONE);
					} else 
						if (browser.contains("android")){
							Session.getInstance().setUserAgent(UserAgent.ANDROID);
						} else
							if (browser.contains("applewebkit")){
								if (browser.contains("ipad")){
									Session.getInstance().setUserAgent(UserAgent.IPAD);
								}
								if (browser.contains("macintosh")){
									Session.getInstance().setUserAgent(UserAgent.MAC);
								}
							}
			}
		}



		//Log.info("userAgent:"+Session.getInstance().getUserAgent());
		//Window.alert("userAgent:"+Session.getInstance().getUserAgent());
		//String country = GeoIp.fetchCountry(Window.Location.getHost());
		String testAgent = Session.getInstance().getTestAgent();
		if (testAgent!=null){
		//Window.alert("host:"+Window.Location.);
			UserAgent userAgent = null;
			if (testAgent.equals(UserAgent.IPHONE.name())){
				Session.getInstance().setUserAgent(UserAgent.IPHONE);
			}
			if (testAgent.equals(UserAgent.ANDROID.name())){
				Session.getInstance().setUserAgent(UserAgent.ANDROID);
			}
		}

		LayoutConstants.getInstance().setSession(Session.getInstance());

		//				testWidget();
		//				if (true)return;

		//		Command callback = new Command(){
		//			public void execute(){
		//				TaxiGangCreatorPC taxiGangCreatorPC= new TaxiGangCreatorPC(); 
		//				//authenticate();
		//				//taxiGangCreatorPC.initUser(Session.getInstance(), RootLayoutPanel.get());
		//				taxiGangCreatorPC.initUser();
		//
		//			}
		//		};

		//StyleSheetLoader.loadStyleSheet(getCSS(), "loader", callback);
		if (Session.getInstance().getCron()!=null){
			GobygangHandler.getInstance().runCron();
			return;
		}

		try{
				GWT.runAsync(new RunAsyncCallback() {
					public void onFailure(Throwable caught) {
						Window.alert("Code download failed");
					}

					public void onSuccess() {
						GobygangPresenter.initUser();
					}
				});

			
		} catch (Exception ex){
			//Log.info("TaxiGangCreator exception"+ex);
		}

	}

	private String setStartCity() {
		String startCity = Window.Location.getParameter("startcity");
		if (startCity==null){
			startCity="";
		}
		if (startCity.equals("DE83646")){
			startCity = "Bad Toelz";
		}
		Session.getInstance().setStartCity(startCity);

		return startCity;
	}

	private String getCSS() {
		String css = Window.Location.getParameter("css");
		return css;
	}



	public static void authenticate(){
		if (Session.getInstance().getUserAgent()==UserAgent.FB || Session.getInstance().getUserAgent()==UserAgent.FB_WEBKIT ){
			Authenication.getInstance().getLogedinResolved(Provider.Google, Status.LoggedOut);
			authenticateFB();
			//FacebookApi.waitForAPI(this,new ThenRenderRestOfApp(),0);
		}else{
			String uri = GWT.getHostPageBaseURL();
			String locale = Session.getInstance().getLocale();
			if(locale != null && !locale.trim().isEmpty()){
				uri += "?locale="+locale;
			}
			//TaxiGangHandler.getInstance().loginToGoogle(uri);
			authenticateFB();
			//FacebookApi.waitForAPI(this,new ThenRenderRestOfApp(),0);					
		}
	}

	private static void authenticateFB(){
		GobygangPresenter.getInstance().myTaxiGang(false);
		//		final AsyncCallback<ConnectState> callback = new GetUserDetailsCallback();
		//		GWT.runAsync(new RunAsyncCallback() {
		//
		//			@Override
		//			public void onSuccess() {
		//				Command command = new Command(){
		//					@Override
		//					public void execute(){
		//						FacebookApi.waitForAPI(new GetUserDetailsCallback());
		//					}
		//				};
		//				FacebookFactory.createFBConnection(callback,command);
		//
		//			}
		//
		//			@Override
		//			public void onFailure(Throwable reason) {
		//				// TODO Auto-generated method stub
		//
		//			}
		//		});
	}



	public static void continueTaxigang(){
		authenticate();
		GobygangPresenter.initUser();

	}
	
}